package com.interview.javabase.thread;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @description: 生产者消费者
 *
 * @author: zhangshuguang@vichain.com
 * @date: 2019/06/14 13:49
 */
public class Demo15 {

    public static void main(String[] args) throws InterruptedException {
        Person person = new Person();
        for (int i = 0; i < 60; i++) {
            new Thread(() ->{
                person.product();
            },String.valueOf(i)).start();
        }

        for (int i = 0; i < 60; i++) {
            new Thread(() ->{
                person.consumer();
            },String.valueOf(i)).start();
        }
    }
}

class Person{

    private Integer number = 0;

    private Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    public void product(){

        lock.lock();
        try {
            while (number != 0){
                condition.await();
            }
            number++;
            System.out.println("生产一条" + number);
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void consumer(){

        lock.lock();
        try {
            while (number == 0){
                condition.await();
            }
            number--;
            System.out.println("消费一条" + number);
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

}